<template>
  <div>
    <el-dialog v-model="dialogVisible" :title="diaTitle" width="500">

      <el-form ref="ruleFormRef" style="max-width: 600px" :model="oneRole" :rules="rules" label-width="auto"
        class="demo-ruleForm" status-icon>
        <el-form-item label="身份名称：" :label-width="formLabelWidth" prop="name">
          <el-input v-model="oneRole.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="状态：" :label-width="formLabelWidth" prop="state">
          <el-radio-group v-model="oneRole.state">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="权限：" :label-width="formLabelWidth">
          <el-tree style="max-width: 600px" ref="treeRef" v-model="oneRole.permissions" :data="allUserMenu"
            show-checkbox node-key="_id" :props="{
              label: 'title',
              children: 'children'
            }" />
        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handOk">
            确认
          </el-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch, computed, watchEffect } from 'vue'
import { ElMessage, type FormRules } from 'element-plus'
import api from "../../../../api/index"
import { RoleItem } from '../../../../api/modules/roleManage';
import { ElTree } from 'element-plus'
import { UserManageItm } from '@/api/modules/authorityMenu';
let { ruleForm } = defineProps(["ruleForm"])
const emit = defineEmits(["getAllRoles"])
const dialogVisible = defineModel()
const treeRef = ref<InstanceType<typeof ElTree>>()
const formLabelWidth = '140px'
interface RuleForm {
  name: string,
  state: boolean
}
// 添加一个角色的对象
let oneRole = ref<RoleItem>({})
// 得到所有的菜单和按钮
let allUserMenu = ref<any[]>([])
// console.log(allUserMan.value,3333);

// 定义表单的验证规则
const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入角色昵称', trigger: 'blur' },
  ],
  state: [
    { required: true, message: '请选择状态', trigger: 'blur' },
  ],
})
// 让弹窗回显
watch(() => ruleForm, () => {
  if (ruleForm._id&&treeRef.value) {
    oneRole.value = ruleForm
    setTimeout(()=>{
      console.log( treeRef.value, 222);
    treeRef.value!.setCheckedKeys( oneRole.value.permissions!.map((item:any)=>item._id))
    },100)
  }
})
watch(dialogVisible, () => {
  if (!dialogVisible.value) {
    oneRole.value = {}
  }
},
  {
    deep: true
  }
)
// watchEffect(()=>{
// if(ruleForm._id&&treeRef.value){
// const permissionsArr = ruleForm.permissions!.map((item:UserManageItm) => {
//     return item._id
//   })
//   console.log(permissionsArr);
//   }
// })
// 弹窗关闭数据清空
// watch(dialogVisible,()=>{
//     if(!dialogVisible.value){
//        oneRole.value={}
//        console.log("没了");
//     }
//   },
// )
onMounted(() => {
  getAllMemuNotPage()
})
// 获取所有菜单
const getAllMemuNotPage = async () => {
  const res = await api.authorityMenu.search({
    creator: "twy"
  })
  if (res.code == 200) {
    console.log(res.data);
    allUserMenu.value = [
      ...res.data.rows
    ]
  }
}
// 添加一个角色
const handOk = () => {
  if (oneRole.value._id) {
    handOkUpdate()
  } else {
    addRole()
  }
}
// 弹窗标题的改变
const diaTitle = computed(() => {
  if (ruleForm._id) {
    return "编辑角色"
  } else {
    return "添加角色"
  }
})
// 点击添加角色
const addRole = async () => {
  const res = await api.roleManage.add({
    ...oneRole.value,
    permissions: treeRef.value!.getCheckedKeys() as string[]
  })
  if (res.code == 200) {
    ElMessage.success("菜单添加成功")
    emit("getAllRoles")
    dialogVisible.value = false
  } else {
    ElMessage.error(res.message)
  }
}

// 点击开始修改角色
const handOkUpdate = async () => {
  const res = await api.roleManage.update({
    ...oneRole.value,
  })
  if (res.code == 200) {
    ElMessage.success("菜单更新成功")
    // 更新成功刷新页面
    emit("getAllRoles")
    console.log("成功了");

    dialogVisible.value = false
  } else {
    ElMessage.error(res.message)
  }
}


</script>

<style scoped></style>